package com.newhope.trade.getway.integration.filter;

import javax.servlet.http.HttpServletRequest;

import com.newhope.trade.getway.integration.vo.base.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.ReflectionUtils;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.newhope.trade.getway.integration.config.FilterConfig;

/**
 * 统一错误拦截器
 * 
 *
 */
public class ExceptionFilter extends ZuulFilter {

	private final Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);
	
	protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

	@Value("${error.path:/error}")
	private String errorPath;

	@Override
	public String filterType() {
		return FilterConfig.FILTER_TYPE_POST;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		// only forward to errorPath if it hasn't been forwarded to already
		return ctx.containsKey("error.status_code")
				&& !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
	}

	@Override
	public Object run() {
		try {
			RequestContext ctx = RequestContext.getCurrentContext();
			HttpServletRequest request = ctx.getRequest();

			int statusCode = (Integer) ctx.get("error.status_code");
			request.setAttribute("javax.servlet.error.status_code", statusCode);

			if (ctx.containsKey("error.exception")) {
				Object e = ctx.get("error.exception");
				logger.warn("Error during filtering", Throwable.class.cast(e));
				request.setAttribute("javax.servlet.error.exception", e);
			}

			if (ctx.containsKey("error.message")) {
				String message = (String) ctx.get("error.message");
				request.setAttribute("javax.servlet.error.message", message);
			}
			writeResponse(ctx);
		}
		catch (Exception ex) {
			ReflectionUtils.rethrowRuntimeException(ex);
		}
		return null;
	}

	private void writeResponse(RequestContext ctx) {
		ctx.setSendZuulResponse(false);
		ctx.setResponseStatusCode(200);
		BaseResponse<Object> res = new BaseResponse<>();
		res.setCode(HttpStatus.SERVICE_UNAVAILABLE.name());
		res.setMsg(HttpStatus.SERVICE_UNAVAILABLE.getReasonPhrase());
		ctx.getResponse().setContentType("text/html;charset=UTF-8");
		ctx.setResponseBody(JSON.toJSONString(res));
	}
	
	public void setErrorPath(String errorPath) {
		this.errorPath = errorPath;
	}
}
